package com.lmhy.base.dao;

import com.google.common.base.Preconditions;
import com.google.common.collect.Lists;
import com.lmhy.base.commons.IOperations;
import org.hibernate.Criteria;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.springframework.util.Assert;

import javax.annotation.Resource;
import java.io.Serializable;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;

/**
 * Desc: show
 * User: 罗铭豪野
 * Time: 2014-12-02 15:58
 */
@SuppressWarnings("unchecked")
public abstract class AbstractHibernateDao<T extends Serializable> implements IOperations<T> {

    private Class<T> clazz;

    @Resource(name="sessionFactory")
    private SessionFactory sessionFactory;

    protected final void setClazz(final Class<T> clazzToSet) {
        this.clazz = Preconditions.checkNotNull(clazzToSet);
    }

    protected final Session getCurrentSession() {
        return sessionFactory.getCurrentSession();
    }

    @Override
    public final T findOne(final long id) {
        return (T)getCurrentSession().get(clazz, id);
    }

    @Override
    public final List<T> findAll() {
        return getCurrentSession().createQuery("from " + clazz.getName()).list();
    }

    @Override
    public final void create(final T entity) {
        Preconditions.checkNotNull(entity);
        getCurrentSession().saveOrUpdate(entity);
    }

    @Override
    public final T update(final T entity) {
        Preconditions.checkNotNull(entity);
        getCurrentSession().update(entity);
        return entity;
    }

    @Override
    public final void delete(final T entity) {
        Preconditions.checkNotNull(entity);
        getCurrentSession().delete(entity);
    }

    @Override
    public final void deleteById(final long entityId) {
        final T entity = findOne(entityId);
        Preconditions.checkState(entity != null);
        delete(entity);
    }
    @Override
    public final List<T> findByList(final String where,Object... objects){
        Preconditions.checkNotNull(where);
        StringBuffer sb = new StringBuffer("from ");
        sb.append(clazz.getName()).append(" where ").append(where);
        Query query = getCurrentSession().createQuery(sb.toString());
        for(int i=0,len=objects.length;i<len;i++){
            query.setParameter(i,objects[i]);
        }
        return query.list();
    }

}
